package com.ruoyi.mall.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.mall.domain.MallOrderOrder;
import com.ruoyi.mall.service.IMallOrderOrderService;
import com.ruoyi.web.controller.utils.XiaochengxuPayService;
import io.swagger.annotations.Api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.mall.domain.MallOrderBack;
import com.ruoyi.mall.service.IMallOrderBackService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 退款单Controller
 * 
 * @author chang
 * @date 2021-11-25
 */
@RestController
@RequestMapping("/mall/mallOrderBack")
public class MallOrderBackController extends BaseController
{
    @Autowired
    private IMallOrderBackService mallOrderBackService;

    @Autowired
    private IMallOrderOrderService orderOrderService;
    /**
     * 查询退款单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderBack:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallOrderBack mallOrderBack)
    {
        startPage();
        List<MallOrderBack> list = mallOrderBackService.selectMallOrderBackList(mallOrderBack);
        return getDataTable(list);
    }

    /**
     * 导出退款单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderBack:export')")
    @Log(title = "退款单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallOrderBack mallOrderBack)
    {
        List<MallOrderBack> list = mallOrderBackService.selectMallOrderBackList(mallOrderBack);
        ExcelUtil<MallOrderBack> util = new ExcelUtil<MallOrderBack>(MallOrderBack.class);
        return util.exportExcel(list, "退款单数据");
    }

    /**
     * 获取退款单详细信息
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderBack:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mallOrderBackService.selectMallOrderBackById(id));
    }

    /**
     * 新增退款单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderBack:add')")
    @Log(title = "退款单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallOrderBack mallOrderBack)
    {
        return toAjax(mallOrderBackService.insertMallOrderBack(mallOrderBack));
    }

    /**
     * 修改退款单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderBack:edit')")
    @Log(title = "退款单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallOrderBack mallOrderBack)
    {
        if ("1".equals(mallOrderBack.getStatus())){
            return refundAgree(mallOrderBack);
        }
        if ("3".equals(mallOrderBack.getStatus())){
            mallOrderBackService.updateMallOrderBack(mallOrderBack);
            return AjaxResult.success("操作完成");
        }
        return AjaxResult.error("错误操作，只能同意或拒绝！");
    }

    public AjaxResult refundAgree(MallOrderBack mallOrderBack) {
        MallOrderBack orderBack = mallOrderBackService.selectMallOrderBackById(mallOrderBack.getId());
        if (orderBack == null) {
            return AjaxResult.error("退款信息异常");
        }
        if (!"0".equals(orderBack.getStatus())) {
            return AjaxResult.error("只有待审核状态才能退款");
        }
        MallOrderOrder orderOrder = orderOrderService.selectMallOrderOrderById(orderBack.getOrderId());
        if (orderOrder == null) {
            return AjaxResult.error("订单信息异常");
        }
        SortedMap<String, String> data = new TreeMap<>();
        //退款到用户微信
        String nonce_str = Md5Utils.getRandomStringByLength(32);
        data.put("nonce_str", nonce_str);
        data.put("out_trade_no", orderOrder.getOrderNo());//商户订单号
        data.put("out_refund_no", orderOrder.getId().toString());//商户退款单号,一笔退款失败后重新提交，请不要更换退款单号，请使用原商户退款单号
        int total_fee = Math.round(Float.valueOf(orderOrder.getPayment().multiply(new BigDecimal(100)).toString()));
        data.put("total_fee", String.valueOf(Math.round(total_fee)));//支付金额，微信支付提交的金额是不能带小数点的，且是以分为单位,这边需要转成字符串类型，否则后面的签名会失败
        data.put("refund_fee", String.valueOf(Math.round(total_fee)));//退款总金额,单位为分,只能为整数
        String str = XiaochengxuPayService.wxXcxRefund(data);
        if (str.length() > 0) {
            return AjaxResult.error(str);
        }

        mallOrderBackService.updateMallOrderBack(mallOrderBack);
        return AjaxResult.success("退款成功");
    }

    /**
     * 删除退款单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderBack:remove')")
    @Log(title = "退款单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mallOrderBackService.deleteMallOrderBackByIds(ids));
    }

    @PostMapping("/handleRefund")
    public ApiResult handleRefund(@RequestBody Map<String, Object> params)
    {
        if (!params.containsKey("refundId")||StringUtils.isEmpty(params.get("refundId").toString())){
            return ApiResult.error("缺少参数");
        }
        Boolean isAccept = orderOrderService.refundStatusRoute(Integer.parseInt("1"),params.get("refundId").toString());
        if (isAccept == true) {
            int status = mallOrderBackService.handleRefund(params);
            return status > 0 ? ApiResult.ok("操作成功") : ApiResult.error("操作失败");
        }else {
            return ApiResult.error("订单异常");
        }
    }
}
